/*
 * Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package top.continew.admin.hanfu.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import top.continew.admin.hanfu.core.oss.OSS;
import top.continew.admin.hanfu.domain.OssFile;
import top.continew.admin.hanfu.domain.Package;
import top.continew.admin.hanfu.domain.bo.PackageBo;
import top.continew.admin.hanfu.domain.dto.PackageDto;
import top.continew.admin.hanfu.domain.vo.PackageVo;
import top.continew.admin.hanfu.domain.vo.wx.PackageWxVo;
import top.continew.admin.hanfu.mapper.PackageMapper;
import top.continew.admin.hanfu.service.IPackageService;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author bbm
 * @since 2025-03-25
 */

@Slf4j
@Service
@RequiredArgsConstructor
public class PackageServiceImpl extends ServiceImpl<PackageMapper, Package> implements IPackageService {

    private final PackageMapper packageMapper;

    private final OSS oss;

    @Override
    public Page<PackageWxVo> getPackageWxVo(Integer pageNum,
                                            Integer pageSize,
                                            String packageName,
                                            String label,
                                            Integer typeId) {

        PackageBo packageBo = new PackageBo();

        packageBo.setPackageName(packageName == null || packageName.isEmpty() ? null : packageName);

        packageBo.setPackageLable(label == null || label.isEmpty() ? null : label);

        packageBo.setPackageTypeId(typeId == 0 ? null : typeId);

        return packageMapper.getPackagePage(new Page<>(pageNum, pageSize), packageBo);
    }

    @Override
    public PackageWxVo getPackageWxDe(Integer id) {
        return packageMapper.getPackageDe(id);
    }

    @Override
    public Page<PackageVo> getPackageListByCondition(Integer pageNum,
                                                     Integer pageSize,
                                                     String packageName,
                                                     String packageTypeMame,
                                                     String label,
                                                     Integer status) {

        PackageBo packageBo = new PackageBo();

        if (packageName.equals("")) {
            packageName = null;
        }

        if (label != null && label.equals("")) {
            label = null;
        }

        if (packageTypeMame.equals("")) {
            packageTypeMame = null;
        }

        packageBo.setPackageName(packageName);
        packageBo.setTypeName(packageTypeMame);
        packageBo.setPackageLable(label);
        packageBo.setStatus(status);
        log.info("PackageBo{}", packageBo);

        return packageMapper.getPackageListByCondition(new Page<>(pageNum, pageSize), packageBo);
    }

    @Override
    public int addPackage(PackageBo packageBo) {

        Package vo = new Package();

        MultipartFile[] multipartFiles = packageBo.getFile().toArray(new MultipartFile[0]);
        List<OssFile> ossFiles = oss.saveFile("packageImg", packageBo.getUpdateBy(), multipartFiles);

        if (ossFiles.isEmpty()) {
            return 0;
        }

        StringBuilder stringBuilder = new StringBuilder();
        ossFiles.forEach(item -> {
            stringBuilder.append(item.getOssId()).append(",");
        });
        stringBuilder.delete(stringBuilder.length() - 1, stringBuilder.length());

        vo.setPackageName(packageBo.getPackageName());
        vo.setPackagePrice(packageBo.getPackagePrice());
        vo.setPackageLable(packageBo.getPackageLable());
        vo.setPackageGoods(packageBo.getPackageGoods());
        vo.setPackageService(packageBo.getPackageService());
        vo.setPackageTrip(packageBo.getPackageTrip());
        vo.setPackageDescription(packageBo.getPackageDescription());
        vo.setPackageTypeId(packageBo.getPackageTypeId());
        vo.setOssIds(stringBuilder.toString());
        vo.setUpdateBy(packageBo.getUpdateBy());
        vo.setUpdateTime(String.valueOf(System.currentTimeMillis()));
        vo.setStatus(packageBo.getStatus());

        boolean save = save(vo);

        return save ? 1 : 0;
    }

    @Override
    public int updatePackage(PackageDto packageDto) {
        boolean update = lambdaUpdate().set(packageDto.getPackageName() != null, Package::getPackageName, packageDto
            .getPackageName())
            .set(Package::getPackagePrice, packageDto.getPackagePrice())
            .set(Package::getPackageLable, packageDto.getPackageLable())
            .set(Package::getPackageGoods, packageDto.getPackageGoods())
            .set(Package::getPackageService, packageDto.getPackageService())
            .set(Package::getPackageTrip, packageDto.getPackageTrip())
            .set(Package::getPackageDescription, packageDto.getPackageDescription())
            .set(Package::getPackageTypeId, packageDto.getPackageTypeId())
            .set(Package::getUpdateBy, packageDto.getUpdateBy())
            .set(Package::getUpdateTime, System.currentTimeMillis())
            .set(Package::getStatus, packageDto.getStatus())
            .eq(Package::getId, packageDto.getId())
            .update();

        return update ? 1 : 0;
    }

    @Override
    public int updatePackageImg(PackageBo packageBo) {
        Package byId = getById(packageBo.getId());

        String[] ossId = byId.getOssIds().split(",");

        List<String> strings = Arrays.stream(packageBo.getOssIds().split(",")).toList();

        List<String> collect = new ArrayList<>();

        //求两个数组之间的差集
        for (String s : ossId) {
            boolean contains = strings.contains(s);
            if (!contains) {
                collect.add(s);
            }
        }

        //删除差集
        oss.deleteFiles(collect);

        List<MultipartFile> file = packageBo.getFile();

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(packageBo.getOssIds()).append(",");
        if (file != null && !file.isEmpty()) {

            List<OssFile> hanfuImg = oss.saveFile("packageImg", packageBo.getUpdateBy(), file
                .toArray(new MultipartFile[] {}));

            for (OssFile ossFile : hanfuImg) {
                stringBuilder.append(ossFile.getOssId()).append(",");
            }

            stringBuilder.delete(stringBuilder.length() - 1, stringBuilder.length());

        }

        boolean update = lambdaUpdate().eq(Package::getId, packageBo.getId())
            .set(!stringBuilder.toString().isEmpty(), Package::getOssIds, stringBuilder.toString())
            .set(Package::getUpdateBy, packageBo.getUpdateBy())
            .set(Package::getUpdateTime, System.currentTimeMillis())
            .update();

        return update ? 1 : 0;
    }

    @Override
    public int deletePackage(ArrayList<Integer> ids) {

        boolean b = removeByIds(ids);
        return b ? 1 : 0;
    }

}
